import { getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators'
import store from '@/store'

const MAX_SIZE = 10

@Module({ dynamic: true, name: 'search', store })
export default class SearchModule extends VuexModule {
  records: string[] = _getLocalStorage() || []

  @Mutation
  updateRecords (record: string) {
    if (!record.trim()) return
    if (this.records.length === MAX_SIZE) {
      this.records.pop()
    }
    this.records.unshift(record)
    // 去除重复记录
    this.records = [...new Set(this.records)]
    _setLocalStorage()
  }

  @Mutation
  clearRecords () {
    this.records = []
    _setLocalStorage()
  }
}

export const searchStore = getModule(SearchModule)

function _setLocalStorage () {
  const str = JSON.stringify(searchStore.records)
  localStorage.setItem('records', str)
}

function _getLocalStorage (): string[] {
  return JSON.parse(localStorage.getItem('records') || '[]')
}
